package com.sbc.Flow;

import java.util.Iterator;
import java.util.concurrent.Flow;

/**
 * @description: 自定义绑定关系
 * @author: songbaicheng
 * @create: 2024-07-30 17:57
 **/
public class SimpleSubscription<T> implements Flow.Subscription {

    private final Flow.Subscriber<? super T> subscriber;
    private final Iterator<T> iterator;
    private boolean cancelled = false;

    public SimpleSubscription(Flow.Subscriber<? super T> subscriber, Iterator<T> iterator) {
        this.subscriber = subscriber;
        this.iterator = iterator;
    }

    @Override
    public void request(long n) {
        if (cancelled) return;
        while (n > 0 && iterator.hasNext()) {
            subscriber.onNext(iterator.next());
            n--;
        }
        if (!iterator.hasNext()) {
            subscriber.onComplete();
        }
    }

    @Override
    public void cancel() {
        cancelled = true;
    }
}
